#!/bin/bash

#OLPC
#gxlxnis@lxptop.org 
#olpc-mesh v0.2 

list() {
	echo -e "          DA                  RA        ok  cost dir rate hop ttl exp(min) snr     precursor"
	for i in `seq 1 200`
	do 
		x=`iwpriv msh0 fwt_list $i`
		echo $x|grep null>/dev/null && break
		printf %2d $i
		echo $x|grep -v null|sed 's/^.*list: //'|sed s/00:00.*$//|awk '
			{printf " "$1"  "$2"  "$3}
			{printf "%5d",$4}
			{printf "   "$5}
			{printf "%5d",$6}
			{printf "   "$9"   "$10" "}
			{printf "%7d", $11/60000}
			{print "    "$13"  "$14}'
	done|sort
}

replace () {
	for i in `seq 1 \`cat $file|wc -l\``
	do
		line=`awk "NR==$i" $file`

		mac=`echo ${line:0:17}|tr '[A-Z]' '[a-z]'`
		name=`echo $line|sed "s/^.*:...//"`

		empty="                  "
		let space=17-${#name}
		let space1=$space/2
		let space2=$space-$space1

		name=`echo -n "${empty:0:$space1}";echo -n "$name";echo "${empty:0:$space2}"`

		cat tmp1|sed "s/$mac/$name/g" > tmp2
		mv tmp2 tmp1
	done
cat tmp1
rm tmp1
}

help () {
cat << EOF
Usage: olpc-mesh [-t FILE]
Display the mesh forwarding tables in a readable manner.

Option:
  
  -t FILE     : Use a MAC/Nick table to replace each address with its Nick.
                The <FILE> must be in the form:
                00:17:C4:XX:XX:XX Nick 1
                00:17:C4:XX:XX:XX Nick 2
                ...

                You may populate the file from the current neighborhood with
		olpc-xos -mac > FILE

EOF
exit
}

echo " $@ "|grep -E "( -h | --help )" > /dev/null && help

[ "$1" = "-t" ] && [ -f "$2" ] && file="$2" && list > tmp1 && replace
[ ! "$1" = "-t" ] || [ ! -f "$2" ] && list 

